#!/usr/bin/env python
# encoding: utf-8
"""
run_tests.py - a test driver for the pybots project to test
MySQLdb and other projects against the TRUNK version of the
python interpreter.

Created by Elliot Murphy on 2006-09-07
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
import os
from os.path import expanduser, splitext
import sys
import getopt
from subprocess import call, STDOUT

help_message = '''
This is a helper script for running MySQLdb as a pyBot
'''

def run_cmd(cmd):
  print "Running command: %s" % cmd
  rc = call(cmd.split(), stderr=STDOUT)
  if rc != 0:
    print "command failed, rc: %i" % rc
  else:
    print "succeeded"
  return rc
  
class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg


def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hv", ["help", ])
        except getopt.error, msg:
            raise Usage(msg)

        # option processing
        print 'received arguments: %s' % argv
        for option, value in opts:
            if option == "-v":
                verbose = True
            if option in ("-h", "--help"):
                raise Usage(help_message)

        # attempt to selfupdate the test script
        # so I can just check in patches to the test
        # script and it will get updated without me
        # needing to login and monkey with the buildslave
        python_tool_dir = os.path.split(argv[0])[0]
        print "updating %s from subversion" % python_tool_dir
        os.system("svn up %s" % python_tool_dir)

        project_dispatcher = {
          'MySQLdb'   : test_mysqldb,
          'psycopg2'  : test_psycopg2,
          'CherryPy'  : test_cherrypy,
          'Storm'     : test_storm,
          }

        if argv[1] in project_dispatcher:
          return project_dispatcher[argv[1]]()
        else:
          print 'This build slave does not know how to test %s' % argv[1]
          return 1

    except Usage, err:
        print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
        print >> sys.stderr, "\t for help use --help"
        return 2

def install_setup_tools():
  print "installing setuptools"
  cmd = "rm -rf setuptools*"
  rc1 = run_cmd(cmd)
  setup_tools_file = 'setuptools-0.6c6.tar.gz'

  cmd = "cp /home/buildslave/%s ." % setup_tools_file
  run_cmd(cmd)
  cmd = "tar xvzf %s" % setup_tools_file
  run_cmd(cmd)
  cmd = "ls"
  run_cmd(cmd)
  cmd = "pwd"
  run_cmd(cmd)
  savedir = os.getcwd()
  os.chdir(
    splitext(splitext(setup_tools_file)[0])[0])

  cmd = "%s setup.py install" % sys.executable
  rc3 = run_cmd(cmd)

  os.chdir(savedir)

  return rc1 or rc3

def test_mysqldb():
  rc0 = install_setup_tools()
  print "testing MySQLdb"
  mysql_python = expanduser("~/mysql-python")
  cmd = "svn up %s" % mysql_python
  rc1 = run_cmd(cmd)
  
  cmd = "rm -rf mysql-python-test"
  run_cmd(cmd)
  
  cmd = "cp -R %s mysql-python-test" % mysql_python
  rc2 = run_cmd(cmd)
  
  savedir = os.getcwd()
  os.chdir("mysql-python-test/trunk/MySQLdb")
  
  cmd = "%s setup.py install" % sys.executable
  rc3 = run_cmd(cmd)
  
  cmd = "%s tests/test_MySQLdb_capabilities.py --verbose" % sys.executable
  rc4  = run_cmd(cmd)

  cmd = "%s tests/test_MySQLdb_dbapi20.py --verbose" % sys.executable
  rc5 = run_cmd(cmd)

  os.chdir(savedir)

  return rc0 or rc1 or rc2 or rc3 or rc4 or rc5

def test_psycopg2():
  print "testing psycopg2"
  psycopg2 = expanduser("~/psycopg/psycopg2/trunk")
  cmd = "svn up %s" % psycopg2
  rc0 = run_cmd(cmd)

  cmd = "rm -rf psycopg2-test"
  run_cmd(cmd)

  cmd = "cp -R %s psycopg2-test" % psycopg2
  rc1 = run_cmd(cmd)

  savedir = os.getcwd()
  os.chdir("psycopg2-test")

  cmd = "%s setup.py build_ext --undef PSYCOPG_DEBUG" % sys.executable
  rc2 = run_cmd(cmd)

  cmd = "%s setup.py install" % sys.executable
  rc3 = run_cmd(cmd)

  os.chdir("tests")

  cmd = "%s test_psycopg2_dbapi20.py" % sys.executable
  rc4 = run_cmd(cmd)

  os.chdir(savedir)

  return rc0 or rc1 or rc2 or rc3 or rc4

def test_cherrypy():
  print 'Testing cherrypy'
  cherrypy = expanduser("~/cherrypy")
  cmd = "svn up %s" % cherrypy
  rc1 = run_cmd(cmd)
  
  cmd = "rm -rf cherrypy"
  run_cmd(cmd)
  
  cmd = "cp -R %s cherrypy" % cherrypy
  rc2 = run_cmd(cmd)
  
  savedir = os.getcwd()
  os.chdir("cherrypy")
  
  cmd = "%s setup.py install" % sys.executable
  rc3 = run_cmd(cmd)
  
  os.chdir("cherrypy/test")
  
  cmd = "%s test.py --dumb" % sys.executable
  rc4 = run_cmd(cmd)
  
  os.chdir(savedir)
  return rc1 or rc2 or rc3 or rc4

def test_storm():
  print 'Testing storm'
  storm = expanduser("~/storm")
  savedir = os.getcwd()
  os.chdir(storm)
  cmd = "bzr pull"
  rc1 = run_cmd(cmd)

  os.environ['STORM_MYSQL_URL'] = 'STORM_MYSQL_URI=mysql://buildslave@localhost/storm_test'
  os.environ['STORM_POSTGRES_URI'] = 'postgres:storm_test'
  cmd = '%s ./test --verbose' % sys.executable
  rc2 = run_cmd(cmd)

  os.chdir(savedir)
  return rc1 or rc2

if __name__ == "__main__":
    sys.exit(main())
